/**
 * <pre>
 * Title: 		SMSListUtil.java
 * Project: 	AgentPortal_1.13.x
 * Author:		linriqing
 * Create:	 	2009-3-24 下午04:18:09
 * Copyright: 	Copyright (c) 2009
 * Company:		Shenzhen Helper
 * <pre>
 */
package com.hengpeng.itfin.sms;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.hengpeng.common.util.MD5;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfin.common.Configuration;
import com.hengpeng.itfin.common.SystemConfigUtil;

/**
 * <pre>
 * 短消息工具
 * </pre>
 * @author linriqing
 * @version 1.0, 2009-3-24
 */
public class SMSUtil
{
	private final static Log logger = LogFactory.getLog(SMSUtil.class);
	
	/**
	 * 银行306定投域名参数名
	 */
	public static final String BANKBUY306_WEBSITE = "bankbuy306.website";
	
	/**
	 * 银行306定投返奖提示天数
	 */
	public static final String BANKBUY306_BONUSDAY = "bankbuy306.bonusday";
	
	/**
	 * 银行306定投机选机选短信发送通道参数名
	 */
	public static final String BANKBUY306_MACHINE_PARTNERID = "bankbuy306.smspartnerid";
	
	/**
	 * 手工添加签名的通道参数名
	 */
	public static final String BANKBUY306_MANUALSIGN = "bankbuy306.manualsign";
	
	/**
	 * 移动、联通、电信的号段配置信息参数名
	 */
	public static final String OPERATOR_PERFIX_CM = "operator.prefix.CM";
	public static final String OPERATOR_PERFIX_CU = "operator.prefix.CU";
	public static final String OPERATOR_PERFIX_CT = "operator.prefix.CT";
	/**
	 * 手机号检验正则表达式
	 */
	public static final String MOBILE_REGEX = "mobile.regex";
	
	/**
	 * 短信接口参数名-content
	 */
	@Deprecated
	public static final String EVENT_SMSPORT_PARANAME_CONTENT = "content";

	/**
	 * 短信接口参数名-phone
	 */
	@Deprecated
	public static final String EVENT_SMSPORT_PARANAME_DIGEST = "digest";

	/**
	 * 短信接口参数名-flag
	 */
	@Deprecated
	public static final String EVENT_SMSPORT_PARANAME_FLAG = "flag";

	/**
	 * 短信接口参数名-phone
	 */
	@Deprecated
	public static final String EVENT_SMSPORT_PARANAME_PHONE = "phone";

	/**
	 * 短信接口参数名-pwd
	 */
	@Deprecated
	public static final String EVENT_SMSPORT_PARANAME_PWD = "pwd";

	/**
	 * 短信接口参数名-username
	 */
	@Deprecated
	public static final String EVENT_SMSPORT_PARANAME_USERNAME = "username";

	/**
	 * 系统参数名-短信接口密码
	 */
	@Deprecated
	public static final String SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_PWD = "SMSPORT_PWD";

	/**
	 * 系统参数名-短信接口地址
	 */
	@Deprecated
	public static final String SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_URL = "SMSPORT_URL";

	/**
	 * 系统参数名-短信接口用户名
	 */
	@Deprecated
	public static final String SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_USERNAME = "SMSPORT_USERNAME";

	/**
	 * 系统参数名-中国移动短信接口地址
	 */
	@Deprecated
	public static final String SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_ZGYD_URL = "SMSPORT_ZGYD_URL";

	/**
	 * 系统参数名-中国移动短信接口用户名
	 */
	@Deprecated
	public static final String SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_ZGYD_USERNAME = "SMSPORT_ZGYD_USERNAME";

	/**
	 * 系统参数名-中国移动短信接口用户名
	 */
	@Deprecated
	public static final String SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_ZGYD_PWD = "SMSPORT_ZGYD_PWD";
	
	@Deprecated
	public static String createXmlString(String id, String timestamp, String mobile, String content)
	{
		String messageId = SystemConfigUtil.getConfigValue(SMSUtil.SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_USERNAME);
		String passwd = SystemConfigUtil.getConfigValue(SMSUtil.SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_PWD);
		String body = "<body><send level=\"0\" mobile=\"" + mobile + "\" content=\"" + content + "\"/></body>";
		String digestSource = messageId + timestamp + passwd + body;
		String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>";
		xml = xml + "<message version=\"1.0\" id=\"" + id + "\"><header>";
		xml = xml + "<messengerID>" + messageId + "</messengerID>";
		xml = xml + "<timestamp>" + timestamp + "</timestamp>";
		xml = xml + "<transactionType>108</transactionType>";
		xml = xml + "<digest>" + MD5.encodeString(digestSource, "UTF-8") + "</digest></header>";
		xml = xml + body + "</message>";
		return xml;
	}
	@Deprecated
	public static String doPost(String urlStr, String parameter, String requestEncode)
	{
		StringBuffer result = new StringBuffer();
		try
		{
			HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
			conn.setConnectTimeout(5000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.connect();
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), requestEncode);
			out.write(parameter);// 这里组织域信息
			out.flush();
			out.close();
			InputStream is = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(is, requestEncode));
			String line = null;
			while ((line = reader.readLine()) != null)
			{
				result.append(line + "\n\r");
			}
			is.close();
			conn.disconnect();
			reader.close();
		}
		catch (Exception e)
		{
			SMSUtil.logger.error(e);
		}
		return result.toString();
	}

	/**
	 * <pre>
	 * 发送短信到手机上
	 * </pre>
	 * @param content 短信内容
	 * @param mobile 手机号码
	 */
	@Deprecated
	public static void doSendSMS(String content, String mobile)
	{
		if (!StringHelper.isEmpty(mobile))
		{
			String smsporturl = SystemConfigUtil.getConfigValue(SMSUtil.SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_URL);
			String id = String.valueOf(System.currentTimeMillis());
			String timestamp = StringHelper.getStringFromDate(new Date(), "yyyyMMddHHmmss");
			String transMessage = createXmlString(id, timestamp, mobile, content);
			String paramenter = "transType=108&transMessage=" + transMessage;
			if ((smsporturl != null) && (smsporturl.length() > 0))
			{
				String smsRsp = SMSUtil.doPost(
						SystemConfigUtil.getConfigValue(SMSUtil.SYSTEMCONFIG_PARANAME_EVENT_SMSPORT_URL), paramenter,
						"UTF-8");
				System.out.println(smsRsp);
				SMSUtil.logger.info("发送事件通知到手机号码{" + mobile + "}响应消息：" + smsRsp);
			}
		}
	}
	
	/**
	 * <pre>
	 * 获取短信签名（移动手机返回空字符串）
	 * </pre>
	 * @param mobile 手机号码
	 * @param partnerId 给用户发送通道ID
	 * @return
	 */
	public static String getManualSign(String mobile, String partnerId)
	{
		if(null == mobile || null == partnerId)
		{
			return "";
		}
		String manualsignStr = Configuration.getValue(SMSUtil.BANKBUY306_MANUALSIGN);
		if (!StringHelper.isEmpty(manualsignStr))
		{
			// 获取多个通道配置
			String[] manualsigns = manualsignStr.split(",");
			for(String manualsign : manualsigns)
			{
				// 获取通道信息
				String[] manualsignArr = manualsign.split("#");
				String manualPartnerId = manualsignArr[0];
				String sign = manualsignArr[1];
				if(null != manualPartnerId && manualPartnerId.equals(partnerId))
				{
					String mobileRegex = Configuration.getValue(SMSUtil.MOBILE_REGEX);
					Pattern p = Pattern.compile(mobileRegex);
					Matcher m = p.matcher(mobile);
					if(m.matches())
					{
						// 移动、联通、电信手机号码段
						String cmSegment = Configuration.getValue(SMSUtil.OPERATOR_PERFIX_CM);
						//String cuSegment = Configuration.getValue(SMSUtil.OPERATOR_PERFIX_CU);
						//String ctSegment = Configuration.getValue(SMSUtil.OPERATOR_PERFIX_CT);
						String mobileSegment = mobile.substring(0, 3);
						if(cmSegment.contains(mobileSegment.concat(",")))
						{
							return "";
						}
						else
						{
							return sign;
						}
					}
					else
					{
						return sign;
					}
				}
			}
		}
		return "";
	}
}
